<?php
declare (strict_types = 1);

namespace app\controller\user\v1;

use app\BaseController;
use think\facade\Db;

class Project extends BaseController
{
    /**
     * 获取项目列表
     * @return \think\Response
     */
    public function getList()
    {

        $data = $this->request->data;
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 10;
        $keyword = $data['keyword'] ?? '';
        $date = $data['date'] ?? '';
        $industry = $data['industry'] ?? '';
        $currentStatus = $data['currentStatus'] ?? 'all';

        $where = [];
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%"];
        }
        if ($industry) {
            $where[] = ['industry', '=', $industry];
        }
        if ($currentStatus !== 'all') {
            $where[] = ['status', '=', $currentStatus];
        }
        if ($date) {
            $where[] = ['createTime', '>=', date('Y-m-d H:i:s', strtotime("-{$date} days"))];
        }

        $list = Db::table('project')
            ->where($where)
            ->page((int)$page, (int)$limit)
            ->field('id,name,createTime,status as statusText')
            ->order('id','desc')
            ->select()
            ->toArray();

        $status = [
            '审核中'=>'pending',
            '已交付'=>'paid',
            '未通过'=>'rejected',
            '优化中'=>'optimizing',
            '未成功'=>'failed',
        ];
        //添加一个firstName 提取nme里面的第一个字符
        foreach ($list as $key => $value) {
            //截图utf8中文字符串的第一个字符    
            $list[$key]['firstName'] = mb_substr($value['name'], 0, 1);
            $list[$key]['status'] = $status[$value['statusText']];
        }

        
        $total = Db::table('project')->where($where)->count();
        
        $data =[
            'list' => $list,
            'total' => $total,
        ];
        return result(SUCCESS, '', $data);
    }

    /**
     * 获取项目详情
     * @return \think\Response
     */
    public function getDetail()
    {
        $id = $this->request->data['projectId'] ;
        $data = $this->request->data;
        $page = (int)$data['page'];
        $limit = (int)$data['limit'];
        
        $info = Db::table('project')
            ->field('id,name,industry,keyword,phone,orderNo,status')
            ->where('id', $id)
            ->where('isDelete', 0)
            ->where('wxappUserUuid', $this->request->uuid)
            ->find();
        if(!$info) return result(FAIL, '项目不存在');

        $keywords = Db::table('projectKeyword')
            ->where('projectId', $id)
            ->where('isDelete', 0)
            ->field('id,business,question,region,status as statusText,regionPath')
            ->page($page, $limit)
            ->select()->toArray();

        $status = [
            '待审核'=>'pending',
            '建设中'=>'building',
            '已上线'=>'using',
            '失效'=>'expired',
            '不通过'=>'reject',
        ];
        foreach ($keywords as $key => $value) {
            $keywords[$key]['status'] = $status[$value['statusText']];
        }
        $info['keywords'] = $keywords;
        return result(SUCCESS, '', $info);
    }
    /**
     * 保存项目（创建/更新）
     * @return \think\Response
     */
    public function save()
    {
        $data = $this->request->data;
        $projectId = $data['id'] ?? "";
        Db::startTrans();
        try {
            $projectData = [
                'name' => $data['name'],
                'industry' => $data['industry'],
                'keyword' => $data['keyword'],
                'phone' => $data['phone'],
            ];

            if($projectId){ 
                //keyword 需要拿本来的数据做对比，如果没了就需要删除，用id做对比
                $oldKeyword = Db::table('projectKeyword')
                ->where('projectId',$projectId)
                ->where('isDelete',0)
                ->column('id');
      
                $newKeyword = array_column($data['keywords'], 'id');
                $deleteKeyword = array_diff($oldKeyword, $newKeyword);  
                if($deleteKeyword){
                    sort($deleteKeyword);
                    Db::table('projectKeyword')->whereIn('id',$deleteKeyword)->where('projectId',$projectId)->update(['isDelete'=>1]);
                }
            }
            
            if ($projectId) {
                // 更新
                Db::table('project')
                    ->where('id', $projectId)
                    ->where('wxappUserUuid', $this->request->uuid)  
                    ->update($projectData);
            } else {
                // 新增
                $projectData['wxappUserUuid'] = $this->request->uuid;
                $projectData['orderNo'] = generateOrderNo();
                $projectId = Db::table('project')->insertGetId($projectData);
            }
            $countCheck  = Db::table('projectKeyword')
            ->where('projectId',$projectId)
            ->where('isDelete',0)
            ->count();
            // 新增时直接添加所有关键词
            $keywordData = [];
            foreach ($data['keywords'] as $keyword) {
                if(isset($keyword['id'])){
                    DB::table('projectKeyword')->where('id',$keyword['id'])->where('projectId',$projectId)->update([
                        'business' => $keyword['business'],
                        'question' => $keyword['question'],
                        'region' => $keyword['region'],
                        'regionPath' => $keyword['regionPath'],
                    ]);
                }else{
                    if ($countCheck >= 10){
                        break;
                    }
                    $keywordData[] = [
                        'projectId' => $projectId,
                        'business' => $keyword['business'],
                        'question' => $keyword['question'],
                        'region' => $keyword['region'],
                        'regionPath' => $keyword['regionPath'],
                    ];
                }
                $countCheck++;
            }
            // 批量插入
            Db::table('projectKeyword')->insertAll($keywordData);
            Db::commit();
            $data['firstName'] = substr($data['name'], 0, 1);
            if(!$projectId){
                $data['createTime'] = date('Y-m-d H:i:s');
            }
            unset($data['keywords'],$data['industry']);
            return result(SUCCESS,  '处理成功！',$data);
        } catch (\Exception $e) {
            Db::rollback();
            return result(FAIL, '处理失败：' . $e->getMessage());
        }
    }

    /**
     * 获取项目列表选项
     * @return \think\Response
     */
    public function getListOptions()
    {
        $dateList = [
            ['text' => '全部', 'value' => ''],
            ['text' => '近七天', 'value' => '7'],
            ['text' => '近一个月', 'value' => '30'],
            ['text' => '近三个月', 'value' => '90'],
            ['text' => '近半年', 'value' => '180'],
            ['text' => '近一年', 'value' => '365']
        ];
        $industryList = Db::table('dicIndustry')
            ->field('value, name as text')
            ->select()->toArray();
        //给industryList的第一个添加全部
        array_unshift($industryList, ['text' => '全部', 'value' => '']);

        return result(SUCCESS, '', [
            'dateList' => $dateList,
            'industryList' => $industryList
        ]);
    }

    /**
     * 获取添加项目选项
     * @return \think\Response
     */
    public function getOptions()
    {
        $industries = Db::table('dicIndustry')->column('name');
        $businesses = Db::table('dicBusiness')->column('name');
        $questions = Db::table('dicQuestion')->column('name');
        $keywordTypes = Db::table('dicKeywordType')->column('name');

        return result(SUCCESS, '', [
            'industries' => $industries,
            'businesses' => $businesses,
            'questions' => $questions,
            'keywordTypes' => $keywordTypes
        ]);
    }

    /**
     * 删除项目
     * @return \think\Response
     */
    public function delete()
    {
        $id = $data['id'] ?? 0;
        $userId = $this->request->uuid;

        if (!$id) {
            return result(FAIL, '参数错误');
        }

        Db::startTrans();
        try {
            Db::table('project')
                ->where('id', $id)
                ->where('user_id', $userId)
                ->delete();

            Db::table('project_keywords')
                ->where('project_id', $id)
                ->delete();

            Db::commit();
            return result(SUCCESS, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return result(FAIL, '删除失败：' . $e->getMessage());
        }
    }
} 